package com.qf.kdgroup.gdbackend.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.kdgroup.gdbackend.dto.ResultBean;
import com.qf.kdgroup.gdbackend.entity.Device;
import com.qf.kdgroup.gdbackend.entity.Worksite;
import com.qf.kdgroup.gdbackend.mapper.DeviceMapper;
import com.qf.kdgroup.gdbackend.mapper.WorksiteMapper;
import com.qf.kdgroup.gdbackend.service.WorksiteService;
import com.qf.kdgroup.gdbackend.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class WorksiteServiceImpl implements WorksiteService {

    @Autowired
    private WorksiteMapper worksiteMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public PageInfo selectAllByPage(PageVO pageVO) {

        PageHelper.startPage(pageVO.getPageNum().intValue(),pageVO.getPageSize().intValue());

        List<Worksite> worksites = worksiteMapper.selectAllByUserid(pageVO.getUserid(),pageVO.getKeyword());

        PageInfo<Worksite> pageInfo = new PageInfo<>(worksites);

        return pageInfo;
    }

    @Override
    public ResultBean deleteById(long wid) {
        List<Device> devices = deviceMapper.selectList(wid,null);

        if (devices.size()>0){
            return ResultBean.error("删除失败，该工地还绑定有设备");
        }

        int res = worksiteMapper.deleteByPrimaryKey(wid);

        return res > 0 ? ResultBean.success("删除成功") : ResultBean.error("删除失败");
    }

    @Override
    public ResultBean add(Worksite worksite) {


        int res = worksiteMapper.insertSelective(worksite);
        return res > 0 ? ResultBean.success() : ResultBean.error();
    }

    @Override
    public ResultBean findByWid(Long wid) {

        Worksite worksite = worksiteMapper.selectByPrimaryKey(wid);

        return ResultBean.success(worksite);
    }

    @Override
    public ResultBean update(Worksite worksite) {


        int res = worksiteMapper.updateByPrimaryKeySelective(worksite);

        return res > 0 ? ResultBean.success() : ResultBean.error();
    }
}
